package com.admin.business.sys;

import com.admin.business.background.venusEmployeeSuspension.VenusEmployeeSuspensionDao;
import com.admin.business.background.venusOrganize.VenusOrganizeDao;
import com.admin.business.background.venusSysUserLog.VenusSysUserLogDao;
import com.admin.business.venusSysUser.VenusSysUserDao;
import com.admin.business.voteUserToken.VoteUserTokenService;
import com.admin.utils.PayUtil.IpUtil;
import com.admin.utils.RedisUtilKey;
import com.admin.utils.constants.CommonConstants;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.tiangong.framework.annotation.OpenApi;
import com.tiangong.framework.bo.CDO;
import com.tiangong.framework.bo.Return;
import com.zmbsms.os.core.util.MD5;
import com.zmbsms.os.core.util.ObjectUtils;
import com.zmbsms.os.core.util.StringUtils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@DS("user")
@Service("userLogin")
@Slf4j
public class userLoginService {

	@Autowired
	private RedisUtilKey redisTemplate;

	@Resource
	VenusSysUserDao venusUser;

	@Resource
	VenusSysUserLogDao venusSysUserLog;

	@Resource
	VenusOrganizeDao venusOrganizeDao;

	@Resource
	VenusEmployeeSuspensionDao venusEmployeeSuspensionDao;

	@Resource
	VoteUserTokenService voteUserTokenService;


	/**
	 * 用户登录（账号/手机号 密码登录）
	 * @Param loginName
	 * @Param loginPwd
	 */
	@OpenApi
	public Return sys_login(CDO cdoRequest) {
		//获取登录手机号
		CDO venusSysUserResult = venusUser.getVenusSysUserByMobile(cdoRequest);
		Return aReturn = loginInformationVerification(cdoRequest, venusSysUserResult);
		if (aReturn.getCode()==400){
			return Return.valueOf(-400,aReturn.getMsg());
		}
		UUID uuid = doLoginStatus(venusSysUserResult);//登录成功之后返回的标识

		//查询 更新信息
		CDO userInfo = venusUser.getVenusSysUserByMobile(cdoRequest);
		venusSysUserResult.set("user_login_times",userInfo.getString("user_login_times"));//'登陆次数'
		venusSysUserResult.set("user_login_forward",userInfo.getString("user_login_forward"));//登陆成功后跳转（1、个人中心 2、物业管理 3、公司管理）
		System.out.println(userInfo.getString("user_head_portrait"));
		if (StringUtils.isEmpty(userInfo.getString("user_head_portrait"))){
			venusSysUserResult.set("user_head_portrait","https://clhy-img.oss-cn-beijing.aliyuncs.com/logo/avatar.jpg");
		}

		/*校验是否存在微信openId 存在表示用户第一次扫码登录，给当前用户手机号绑定微信openId  zsg*/
		 updateWechatOpenId(cdoRequest.getString("openId"), 1, cdoRequest.getLong("loginName"));

		/*校验是否存在微信openId 存在表示用户第一次微信授权登录，给当前用户手机号绑定微信openId*/
		 updateWechatOpenId(cdoRequest.getString("openIds"), 2, Long.parseLong(venusSysUserResult.getString("user_id")));

		//记录操作日志
		addOpperationLog(venusSysUserResult.getString("user_id"));

		Map<String,Object> map = new HashMap<>();
		map.put("user",venusSysUserResult);
        //如果标识不为空 前端标识 1为业主 2为普通用户 ,
		String logotype = cdoRequest.getString("logotype");
		if (StringUtils.isNotEmpty(logotype)){
			/**
			 * 这个留着如果业主和普通用户有新逻辑可以在下面写或写成方法
			 *  logotype 1.业主 2.普通用户 3.商户
			 */
			String name=null;
			if (logotype.equals("1")){
				//业主
				name="owner";
			}else if (logotype.equals("2")){
				//普通用户
				name="ordinary";
			}else if (logotype.equals("3")){
				//商户
				name="commercial";
			}
			//====
			map.put("true",true);
			map.put("uuid",uuid);
			return Return.valueOf(200, "登录成功！", map);
		}
		//结束公司数组
		List<CDO> organizeList =new ArrayList<>();
		//查询当前用户是否有存在的公司
		organizeList= companyWhetherNotExists(Long.parseLong(venusSysUserResult.getString("user_id")));
		//检查此用户是否存在停职情况（判断是否可以登录、和停职截止时间）
		organizeList =userWhetherDimission(Long.parseLong(venusSysUserResult.getString("user_id")), organizeList);
		map.put("venusOrganizeList",organizeList);
		map.put("uuid",uuid);
		if(ObjectUtils.isNotNull(organizeList)){
//			存储当前公司id
			redisTemplate.set("org_"+uuid, organizeList.get(0).getInteger("org_id")+"",2592000L);
			map.put("true",true);
		}else{
			map.put("true",false);
			return Return.valueOf(200, "该用户暂未注册企业公司",map );
		}
		return Return.valueOf(200, "登录成功！", map);
	}

	/**
	 *  校验信息 手机和登录信息
	 * @return
	 */
	public Return loginInformationVerification(CDO cdoRequest,CDO venusSysUserResult){

		//校验账号是否存在
		if (ObjectUtils.isNull(venusSysUserResult)){
			return Return.valueOf(400, "您输入的账号不存在，请您先注册！", "");
		}
		//获取登录手机号
		if (StringUtils.isEmpty(cdoRequest.getString("loginName"))){
			return Return.valueOf(400, "您没有填写您的手机号码！", "loginName");
		}
		//手机号正则验证
		Boolean mobileCheck = Pattern.matches("^[1][35789][0-9]{9}$",cdoRequest.getString("loginName"));
		if (!mobileCheck){
			return Return.valueOf(400, "您填写的账号信息不正确！", "loginName");
		}
		//检验账号状态
		if (venusSysUserResult.getString("user_status").equals("2")){
			return Return.valueOf(400, "您目前处于锁定状态，暂不能登录系统！", "");
		}
		//获取用户输入loginPwd
		String loginPwd = cdoRequest.getString("loginPwd");
		if (StringUtils.isEmpty(loginPwd)){
			return Return.valueOf(400, "您输入的密码不能为空!", "loginPwd");
		}
		if (StringUtils.isEmpty(cdoRequest.getString("wxLogins"))){
			//校验密码开始
			if (!MD5.getMD5(loginPwd).equals(venusSysUserResult.getString("user_pwd"))){
				return Return.valueOf(400, "您输入的密码不正确，请您重新输入！", "loginPwd");
			}
		}

		return Return.valueOf(cdoRequest);
	}


	/**
	 * 记录操作日志
	 */
//
	public void addOpperationLog(String userId){
		CDO addVSUL=new CDO();
		addVSUL.set("sys_user_id",userId);//查询当前用户usetr_id
		addVSUL.set("log_type",CommonConstants.LOG_TYPE);//登录类型
		addVSUL.set("log_operation",CommonConstants.LOG_TYPE);//操作内容
		addVSUL.set("log_ip",IpUtil.getIpAddress());//需要获取当前电脑的IP工具类
		addVSUL.set("log_result","登录成功");
		venusSysUserLog.addVenusSysUserLog(addVSUL);
	}


	/**
	 * @param openId 微信openid
	 * @param type  1.手机号  2. 登录user_id
	 * @param item 信息
	 */
	public void  updateWechatOpenId(String openId,Integer type, Long item){

		if (!StringUtils.isEmpty(openId)){
			CDO cdo = new CDO();
			if (type.equals(1)){
				/*校验是否存在微信openId 存在表示用户第一次扫码登录，给当前用户手机号绑定微信openId  zsg*/
				cdo.set("openId", openId);
				cdo.set("userTel",item);
				 venusUser.updateUserOpenIdByPhoneNumber(cdo);

			}else if (type.equals(2)){
				/*校验是否存在微信openId 存在表示用户第一次微信授权登录，给当前用户手机号绑定微信openId*/
				cdo.set("user_id",item);
				cdo.set("open_id",openId);
				cdo.set("state",1);//1代表是pc端 2app  zwl  2022-10-31
				venusUser.insertUserOpenId(cdo);
			}
		}

	}


	/**
	 * 查询当前用户是否有存在的公司
	 */
	public  List<CDO> companyWhetherNotExists(Long UserId){
		List<CDO> orgList = venusOrganizeDao.getVenusOrgByUser(UserId);
		List<CDO> venusOrganizeList=new ArrayList<>();
		if (ObjectUtils.isNotNull(orgList)) {
			for (CDO cdo : orgList) {
				CDO result = venusOrganizeDao.getVenusOrganizeByUserListId(cdo.getString("org_id"));
				System.out.println(result + "--dad1");
				if (ObjectUtils.isNotNull(result)) {
					if (result.getInteger("org_parent_id") > 0) {
						CDO resultP = venusOrganizeDao.getVenusOrganizeByUserListId(result.getString("org_parent_id"));
						if (ObjectUtils.isNotNull(resultP)) {
							if (resultP.getInteger("org_parent_id").longValue() > 0) {
								CDO resultPtwo = venusOrganizeDao.getVenusOrganizeByUserListId(resultP.getString("org_parent_id"));
								venusOrganizeList.add(resultPtwo);
							} else {
								venusOrganizeList.add(resultP);
							}
						}
					} else {
						venusOrganizeList.add(result);
					}
				}
			}
		}

		//去重信息
		venusOrganizeList=venusOrganizeList.stream().distinct().collect(Collectors.toList());
		return venusOrganizeList;
	}

	/**
	 *  检查此用户是否存在停职情况（判断是否可以登录、和停职截止时间）
	 * @param userId 登录用户user_id
	 * @param cdo  公司数组
	 * @return
	 */
	public List<CDO>  userWhetherDimission(Long userId,List<CDO> cdo){

		//根据用户id获取当前员工停职
		List<CDO> suspensionList=venusEmployeeSuspensionDao.getSuspensionList(userId);
		if (ObjectUtils.isNotNull(suspensionList) && ObjectUtils.isNotNull(cdo)){
			Date now=new Date();
			for (int i =cdo.size()-1;i>=0;i--){
				for (CDO suspension:suspensionList){
					if (cdo.get(i).getInteger("org_id")==suspension.getInteger("org_id")){//代表在此公司有停职
						if (suspension.getInteger("login_sign")==1 && suspension.getDate("end_time").getTime()<=now.getTime()){ //在截止日期之后不可以登录
							cdo.remove(i);
							break;
						}
					}
				}
			}
		}
		return cdo;
	}



	/**
	 * 存储 用户登录信息
	 * @param cdo
	 * @return
	 */
	public UUID doLoginStatus(CDO cdo) {

		//标识
		UUID uuid = UUID.randomUUID();

		//登录添加token 信息
		CDO token=new CDO();
		token.set("user_id",cdo.getString("user_id"));
		token.set("user_id_zyw",cdo.getString("user_id_zyw"));
		token.set("token_value",uuid.toString());
		token.set("token_state",0);
		token.set("effective_time",getsEndTime(1));
		voteUserTokenService.addUpdateUserToken(token);

		//重新存储redis信息 根据数据存存储的token_value 或者前端存储的uuid 从redis获取用户信息
		redisTemplate.set(uuid.toString(), cdo);//登录时长为永久

		CDO upUserLong=new CDO();
		upUserLong.set("user_id",cdo.getString("user_id"));
		//登录成功后，登录次数+1，并且记录最后一次登录时间
		venusUser.updateSysUserLoginTimes(upUserLong);
		return uuid;
	}


	/**
	 *   根据不同状态 设置 时间 1 默认8 小时
	 * @param type
	 * @return
	 */
	public Date getsEndTime(Integer type) {
		// 创建一个 Calendar 实例
		Calendar calendar = Calendar.getInstance();
		// 获取当前时间
		Date currentDate = new Date();
		// 设置 Calendar 的时间为当前时间
		calendar.setTime(currentDate);
		if(type.equals(1)){
			// 将当前时间加上8小时
			calendar.add(Calendar.HOUR_OF_DAY, 8);
		}
		// 获取加上8小时后的时间
		Date newDate = calendar.getTime();

		return newDate;
	}




	@OpenApi
	public Return getTestRedisTemplateInfo(CDO cdo) {
		UUID uuid = UUID.randomUUID();
		CDO venusSysUserByMobile = venusUser.getVenusSysUserByMobile(cdo);
//		存储uuid 测试
		redisTemplate.set(uuid.toString(),venusSysUserByMobile);
		Object o = redisTemplate.get(uuid.toString());
		CDO cdoCopy = CDO.copyToNewCDO(o);
		System.out.println(cdoCopy);


//		获取存储 公司测试
		redisTemplate.set("org_"+uuid,"53",2592000L);
		Object value=redisTemplate.get("org_"+uuid);
		CDO cdo2 = CDO.copyToNewCDO(value);
		System.out.println(cdo2);


		CDO cod5=new CDO();
		cod5.set("cdo",cdo);
		cod5.set("cdo2",cdo2);

		return Return.valueOf(cod5);

	}

}
